package kr.hkit.framework.dao;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class LoadPropertyDAO {
	private static final Properties PROPERTIES = new Properties();
	private static final String PROPERTIES_FILE = "dao.properties";
	
	private static String DRIVER;
	private static String URL;
	private static String USER;
	private static String PASSWORD;
	
	private static LoadPropertyDAO instance = new LoadPropertyDAO();
	
	private LoadPropertyDAO(){
		InputStream is;
		try {
			is = new BufferedInputStream(new FileInputStream(new File(PROPERTIES_FILE)));
			PROPERTIES.load(is);
			DRIVER = PROPERTIES.getProperty("DRIVER");
			URL = PROPERTIES.getProperty("URL")+PROPERTIES.getProperty("DATABASE");
			USER = PROPERTIES.getProperty("USER");
			PASSWORD = PROPERTIES.getProperty("PASSWORD");
			
			Class.forName(DRIVER);
		} catch (FileNotFoundException e) {
			throw new DAOConfigurationException(PROPERTIES_FILE + "' is not found", e);
		} catch (IOException e) {
			throw new DAOConfigurationException("Cannot load to properties file '" + PROPERTIES_FILE + "'." , e);
		} catch (ClassNotFoundException e) {
			throw new DAOConfigurationException("Driver class '" + DRIVER + "' is missing in classpath" ,e);
		}
	}
	
	private Connection createConnection() throws DAOConfigurationException{
		Connection connection = null;
		try {
			connection = DriverManager.getConnection(URL, USER, PASSWORD);
		} catch (SQLException e) {
			throw new DAOConfigurationException("ERROR: Unable to Connect to Database." , e);
		}
		return connection;
	}
	
	public static Connection getConnection() throws DAOConfigurationException{
		return instance.createConnection();
	}
	
}
